package com.css.dzj.dzjwgr.modules.appeal.service.impl;

import com.alibaba.fastjson.JSON;
import com.css.dzj.dzjwgr.common.util.Constant;
import com.css.dzj.dzjwgr.common.util.HttpClientUtil;
import com.css.dzj.dzjwgr.common.util.ServiceUtil;
import com.css.dzj.dzjwgr.common.util.excel.ExcelData;
import com.css.dzj.dzjwgr.common.util.excel.ExportExcelUtils;
import com.css.dzj.dzjwgr.modules.appeal.entity.JgWgrTsjbglEntity;
import com.css.dzj.dzjwgr.modules.appeal.entity.QJgWgrTsjbglEntity;
import com.css.dzj.dzjwgr.modules.appeal.mapper.appealMapper;
import com.css.dzj.dzjwgr.modules.appeal.service.appealService;
import com.css.dzj.dzjwgr.modules.appeal.vo.PortalMsgEntity;
import com.css.dzj.dzjwgr.modules.updown.entity.QCommAttachmentEntity;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class appealServiceImpl implements appealService {
    //注入JPAQueryFactory工厂
    @Autowired
    JPAQueryFactory jpaQueryFactory;
    @Autowired
    private appealMapper appealMapper;

    @Override
    public JgWgrTsjbglEntity queryOne(String id) {
        QJgWgrTsjbglEntity q = QJgWgrTsjbglEntity.jgWgrTsjbglEntity;
        JgWgrTsjbglEntity One = jpaQueryFactory
                                .selectFrom(q)
                                .where(q.id.eq(id)
                                //q..delFlag.eq(Constant.NO_DELETE)
                                )
                                .fetchOne();
        return One;
    }

    @Override
    @Transactional
    public String fk(String id,String mainUrl) {
        JgWgrTsjbglEntity appeal = queryOne(id);
        if(appeal.getAppealStatus().equals("2")){
            String msg = "1";
            return msg;
        }else {
            appeal.setAppealStatus("2");
            appealMapper.save(appeal);
            String url = mainUrl + "/message/save";
            PortalMsgEntity portalMsgEntity = new PortalMsgEntity();
            portalMsgEntity.setComplainContent(appeal.getRecords());
            portalMsgEntity.setComplainStatus(appeal.getAppealStatus());
            portalMsgEntity.setComplainTime(appeal.getCreatTime());
            portalMsgEntity.setComplainTopic(appeal.getName() + "的投诉");
            portalMsgEntity.setCreateTime(new Date());
            portalMsgEntity.setComplainUser(appeal.getName());
            portalMsgEntity.setDealTime(new Date());
            portalMsgEntity.setDelFlag("0");
            portalMsgEntity.setLinkId(id);
            String Message = JSON.toJSONString(portalMsgEntity);
            String msg = HttpClientUtil.doPostJson(url, Message);
            return msg;
        }
    }

    @Override
    public String addReply(JgWgrTsjbglEntity jgWgrTsjbglEntity) {
        jgWgrTsjbglEntity.setCreatTime(new Date());
        //提交状态
        jgWgrTsjbglEntity.setAppealStatus("1");
        jgWgrTsjbglEntity.setDelStatus(Constant.NO_DELETE);
        /**
         * 是否存在附件，设置默认值
         */
        String id = jgWgrTsjbglEntity.getId();
        QCommAttachmentEntity q = QCommAttachmentEntity.commAttachmentEntity;
        int count = (int)jpaQueryFactory.selectFrom(q).where(q.tableUuid.eq(id)).fetchCount();
        if (count > 0){
            jgWgrTsjbglEntity.setCommentCode("是");
        }else {
            jgWgrTsjbglEntity.setCommentCode("否");
        }
        try {
            appealMapper.save(jgWgrTsjbglEntity);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public QueryResults<JgWgrTsjbglEntity> getPage(Pageable pageable, String name, String appealStatus, String records, String startTime, String endTime) {
        QJgWgrTsjbglEntity q = QJgWgrTsjbglEntity.jgWgrTsjbglEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        predicate = (name == null || name.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.name.like("%" + name + "%"));
        predicate = (appealStatus == null || appealStatus.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.appealStatus.eq(appealStatus));
        predicate = (records == null || records.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.records.like("%" +records + "%"));
       //反馈人员只能查看到已经提交和已反馈的投诉
        predicate = ExpressionUtils.and(predicate, q.appealStatus.ne("0"));
        if((StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            System.out.println();
            try {
                endDate = sf.parse(endTime + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.creatTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            System.out.println();
            try {
                startDate = sf.parse(startTime+" "+"00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.creatTime.between(startDate,endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                System.out.println();
                startDate = sf.parse(startTime+" "+"00:00:00.000");
                endDate = sf.parse(endTime + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.creatTime.between(startDate,endDate));
        }

        return jpaQueryFactory.selectFrom(q).
                where(predicate).
                orderBy(q.creatTime.desc()).
                offset(pageable.getOffset()).
                limit(pageable.getPageSize()).
                fetchResults();
    }

    @Override
    public List<JgWgrTsjbglEntity> queryByIds(String ids) {
        if(com.alibaba.druid.util.StringUtils.isEmpty(ids)){
            throw new RuntimeException("ids为空!");
        }
        List<String> idList = Arrays.asList(ids.split(","));
        return appealMapper.findAllById(idList);
    }

    @Override
    public List<JgWgrTsjbglEntity> queryByParams(String records,String name,String startTime, String endTime,String appealStatus) {
        List<JgWgrTsjbglEntity> list = new ArrayList<>();
        QJgWgrTsjbglEntity q = QJgWgrTsjbglEntity.jgWgrTsjbglEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        predicate = (records == null || records.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.records.like("%" + records + "%"));
        predicate = (name == null || name.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.name.like("%" + name + "%"));
        predicate = (appealStatus == null || appealStatus.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.appealStatus.eq(appealStatus));
        //反馈人员只能查看到已经提交和已反馈的投诉
        predicate = ExpressionUtils.and(predicate, q.appealStatus.ne("0"));
        if((StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(endTime + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.creatTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            System.out.println();
            try {
                startDate = sf.parse(startTime+" "+"00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.creatTime.between(startDate,endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                System.out.println();
                startDate = sf.parse(startTime+" "+"00:00:00.000");
                endDate = sf.parse(endTime + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.creatTime.between(startDate,endDate));
        }

        list = jpaQueryFactory.selectFrom(q).
                where(predicate).
                orderBy(q.creatTime.desc()).
                fetch();
        return  list;
    }

    @Override
    public void exportAppealToExcel(HttpServletResponse response, List<JgWgrTsjbglEntity> jgWgrTsjbglEntities) {
        if (jgWgrTsjbglEntities == null || jgWgrTsjbglEntities.size() < 0) {
            throw new RuntimeException("投诉举报集合为空");
        }
        // 创建导出实体
        ExcelData data = new ExcelData();
        data.setName("投诉举报信息表");
        /**
         * 设置Excel标题
         */
        ArrayList<String> titles = new ArrayList<>();
        titles.add("投诉人");
        titles.add("投诉时间");
        titles.add("投诉状态");
        titles.add("联系电话");
        titles.add("性别");
        titles.add("省");
        titles.add("市");
        titles.add("县");
        titles.add("违法活动记录");
        data.setTitles(titles);
        /**
         * 处理行数据
         */
        ArrayList<List<Object>> rows = new ArrayList<>();
        for (JgWgrTsjbglEntity tsjbglEntity: jgWgrTsjbglEntities) {
            ArrayList<Object> row = new ArrayList<>();
            row.add(tsjbglEntity.getName());
            SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
            String formaTime = spf.format(tsjbglEntity.getCreatTime());
            row.add(formaTime);
            if("0".equals(tsjbglEntity.getAppealStatus())){
                row.add("未提交");
            }else if("1".equals(tsjbglEntity.getAppealStatus())){
                row.add("待处理");
            }else if("2".equals(tsjbglEntity.getAppealStatus())){
                row.add("已处理");
            }
            row.add(tsjbglEntity.getPhone());
            row.add(tsjbglEntity.getSex());
            row.add(tsjbglEntity.getProvince());
            row.add(tsjbglEntity.getCities());
            row.add(tsjbglEntity.getCounty());
            row.add(tsjbglEntity.getRecords());
            rows.add(row);
        }
        data.setRows(rows);
        try {
            // 导出
            ExportExcelUtils.exportExcel(response, "投诉举报信息表.xlsx", data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public QueryResults<JgWgrTsjbglEntity> getPageByName(Pageable pageable, HttpServletRequest request, String name, String appealStatus, String records, String startTime, String endTime,String loginName) {
        QJgWgrTsjbglEntity q = QJgWgrTsjbglEntity.jgWgrTsjbglEntity;
      //  String loginName= ServiceUtil.getLoginName(request);
        Predicate predicate=q.isNotNull().or(q.isNull());
        predicate = (name == null || name.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.name.like("%" + name + "%"));
        predicate = (appealStatus == null || appealStatus.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.appealStatus.eq(appealStatus));
        predicate = (records == null || records.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.records.like("%" +records + "%"));
        if((StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            System.out.println();
            try {
                endDate = sf.parse(endTime + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.creatTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(StringUtils.isEmpty(endTime))){
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            System.out.println();
            try {
                startDate = sf.parse(startTime+" "+"00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.creatTime.goe(startDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                System.out.println();
                startDate = sf.parse(startTime+" "+"00:00:00.000");
                endDate = sf.parse(endTime + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.creatTime.between(startDate,endDate));
        }
        return jpaQueryFactory.selectFrom(q).where(q.name.eq(loginName),predicate).orderBy(q.creatTime.desc()).
                offset(pageable.getOffset()).
                limit(pageable.getPageSize()).
                fetchResults();
    }
    /**
     * 修改公示通报信息
     */
    @Override
    @Transactional
    public void update(JgWgrTsjbglEntity jgWgrTsjbglEntity) {

    }

    @Override
    public String zcReply(JgWgrTsjbglEntity jgWgrTsjbglEntity) {
        jgWgrTsjbglEntity.setCreatTime(new Date());
        //提交状态
        jgWgrTsjbglEntity.setAppealStatus("0");
        jgWgrTsjbglEntity.setDelStatus(Constant.NO_DELETE);
        /**
         * 是否存在附件，设置默认值
         */
        String id = jgWgrTsjbglEntity.getId();
        QCommAttachmentEntity q = QCommAttachmentEntity.commAttachmentEntity;
        int count = (int)jpaQueryFactory.selectFrom(q).where(q.tableUuid.eq(id)).fetchCount();
        if (count > 0){
            jgWgrTsjbglEntity.setCommentCode("是");
        }else {
            jgWgrTsjbglEntity.setCommentCode("否");
        }
        try {
            appealMapper.save(jgWgrTsjbglEntity);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String getAppealCount() {
        QJgWgrTsjbglEntity q = QJgWgrTsjbglEntity.jgWgrTsjbglEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        //反馈人员只能查看到已经提交和已反馈的投诉
        predicate = ExpressionUtils.and(predicate, q.appealStatus.ne("0"));
        Long l = jpaQueryFactory.select(q.id.count()).from(q).where(predicate).fetchCount();
        if(l!=null){
            return  l.toString();
        }
        return "0";
    }
}
